package com.fanketly.funacg2.ui.screen

import android.util.Log
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.paging.LoadState
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.itemKey
import com.fanketly.funacg2.R
import com.fanketly.funacg2.data.TAG
import com.fanketly.funacg2.data.model.conventToWork
import com.fanketly.funacg2.ui.components.SwipeToDelete
import com.fanketly.funacg2.ui.screen.destinations.FavouriteScreenDestination
import com.fanketly.funacg2.ui.screen.destinations.LoginScreenDestination
import com.fanketly.funacg2.ui.viewmodels.FavouriteViewModel
import com.fanketly.funacg2.ui.viewmodels.HomeViewModel
import com.fanketly.funacg2.ui.viewmodels.isFavouriteChange
import com.fanketly.funacg2.utils.ToastUtils
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import com.ramcosta.composedestinations.navigation.popUpTo

@OptIn(ExperimentalFoundationApi::class)
@Destination
@Composable
fun FavouriteScreen(
    homeViewModel: HomeViewModel,
    favouriteViewModel: FavouriteViewModel = hiltViewModel(),
    navigator: DestinationsNavigator,
) {
    val data = favouriteViewModel.pager.collectAsLazyPagingItems()
    var showDialog by remember {
        mutableStateOf<String?>(null)
    }

    LaunchedEffect(key1 = data.loadState.refresh, block = {
        val refresh = data.loadState.refresh

        if (refresh is LoadState.Error) {
            val localizedMessage = refresh.error.localizedMessage ?: return@LaunchedEffect
            if (localizedMessage.contains("401")) {
                navigator.popBackStack()
                //跳转到登录页面
                navigator.navigate(LoginScreenDestination)
                ToastUtils.shortToast("请先进行登录")
            } else {
                showDialog = "发生错误，${localizedMessage}"
            }
            Log.i(TAG, "FavouriteScreen: $localizedMessage")
        }
    })
    if (showDialog != null) AlertDialog(onDismissRequest = { showDialog = null }, confirmButton = {
        TextButton(onClick = { }) {
            Text(text = stringResource(id = R.string.confirm))
        }
    }, text = { Text(text = showDialog ?: "发生错误，是否重新加载") })
    LazyColumn(
        modifier = Modifier
            .fillMaxSize()
            .padding(top = 8.dp)
    ) {
        items(data.itemCount, key = data.itemKey { it.id }) { index ->
            val workEntity = data[index]
            if (workEntity != null) SwipeToDelete(
                Modifier.animateItemPlacement(),
                title = workEntity.title,
                thumbnailCoverUrl = workEntity.img,
                dismissedToEnd = homeViewModel::openDrawer,
                onDelete = {
                    Log.i(TAG, "FavouriteScreen: " + data.loadState.toString())
                    favouriteViewModel.cancelFavourite(workEntity.asmrId) {
                        data.refresh()
                    }
                }) {
                homeViewModel.getAudio(workEntity.conventToWork())
            }
        }
    }
    LaunchedEffect(key1 = Unit, block = {
        if (isFavouriteChange) {
            isFavouriteChange = false
            navigator.navigate(FavouriteScreenDestination) {
                popUpTo(NavGraphs.root) {
                }
                launchSingleTop = true
            }
            Log.i(TAG, "FavouriteScreen:isChange: ")
        }
    })
}
